package com.cyzy.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.dto.Result;

import com.cyzy.mapper.StudentMapper;
import com.cyzy.pojo.Student;
import com.cyzy.service.StudentService;
import com.cyzy.utils.RedisUtil;
import com.cyzy.utils.SHA256Utils;
import com.cyzy.utils.TokenUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {


    @Autowired
     StudentMapper studentMapper;
    
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TokenUtils tokenUtils;
    


    @Override
    public Student login(String acc, String pwd) {
        LambdaQueryWrapper<Student> eq = new LambdaQueryWrapper<Student>()
                .eq(Student::getStudentPhone, acc) // student.getUserAcc   实体类 :: getUserAcc, 值  student.get where user_acc = #{acc}
                .eq(Student::getStudentPwd, pwd);
        Student student = studentMapper.selectOne(eq);
        return student;
    }

    @Override
    public Result insertUser(Student student) {
        Student user1 = studentMapper.selectOne(new LambdaQueryWrapper<Student>());
        if(user1 != null){
            return Result.error().message("手机号已存在");
        }
        studentMapper.insert(student);
        return Result.ok().data("student", student);
    }

    @Override
    public Result getEmail(Student student) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<Student>()
                .eq(Student::getStudentEmail, student.getStudentEmail());
        Student one = studentMapper.selectOne(wrapper);
        if(one == null){
            return Result.error().message("未注册邮箱, 请检查邮箱");
        }
        Boolean b = redisTemplate.hasKey(SHA256Utils.encryptPassword(student.getStudentEmail()));
        if(Boolean.TRUE.equals(b)){
            return Result.error().message("已发送邮件，请等待5分钟后在发送");
        }


        int max = 99999;
        int min = 10000;

        Random random = new Random();
        int  code = random.nextInt(max - min + 1) + min;
        Map<String, Object> sent = new HashMap<>();
        sent.put("code", code);
        sent.put("to", student.getStudentEmail());
        sent.put("templateId", 1);
        sent.put("userName", one.getStudentName());

        // 生成 JSON 字符串
        String jsonString = JSON.toJSONString(sent);
        System.out.println(jsonString);  // 输出结果，用于调试

        redisTemplate.opsForSet().add(SHA256Utils.encryptPassword(student.getStudentEmail()), ""+code);
        // 设置 Key 的过期时间为 5 分钟
        redisTemplate.expire(SHA256Utils.encryptPassword(student.getStudentEmail()), 5, TimeUnit.MINUTES);


//        sent.put("")
        rocketMQTemplate.convertAndSend("emil-topic", jsonString);
        return Result.ok().message("邮件已发送");
    }

    @Override
    public Result emilLogin(Student student) {
        Boolean b = redisTemplate.hasKey(SHA256Utils.encryptPassword(student.getStudentEmail()));
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<Student>()
                .eq(Student::getStudentEmail, student.getStudentEmail());
        Student one = studentMapper.selectOne(wrapper);
        if(one == null){
            return Result.ok().message("未注册邮箱, 请检查邮箱");
        }
        if(Boolean.FALSE.equals(b)){
            return Result.error().message("验证码错误");
        }
        Boolean member = redisTemplate.opsForSet()
                .isMember(SHA256Utils.encryptPassword(student.getStudentEmail()), student.getCode());
        if(!member){
            return Result.error().message("验证码错误");
        }
        String token = tokenUtils.generateToken(one.getStudentId() + "");

        redisTemplate.delete(SHA256Utils.encryptPassword(student.getStudentEmail()));
        redisUtil.set(token, one.getStudentId() + "");
        return Result.ok().message("登录成功").data("login", one).data("token", token);
    }
}
